#!/opt/ActivePerl-5.8/bin/perl -w
use strict;
use YAML;
use Data::Dumper;
  use Devel::Size qw(size total_size);
use File::Copy; 
use SecurityCenter;
use CenterFactory;
use DataCollectionChannel;
use CollectionChannelFactory; 
use DataDumpingManager; 
use Log::Log4perl ;
use IO::Compress::Gzip qw(gzip $GzipError); 
use Date::Manip;
use POSIX qw(strftime getpid);
use threads;
use threads::shared;
use Thread::Queue;


# configuration files
my $configuration_dir = "configuration";
my $channel_config_file = $configuration_dir . "/collection_channels.conf";
my $center_config_file = $configuration_dir . "/security_centers.conf";
my $log_config_file = $configuration_dir . "/log.conf";
my $database_config_file = $configuration_dir . "/data_access.conf";
my $dump_file = ".mobisec.dat";

# init the logger
#Log::Log4perl->init($log_config_file);
#our $logger = Log::Log4perl::get_logger();
#my $logfile = Log::Log4perl->appender_by_name('LOGFILE')->filename();
#my $archfile = strftime('%d%m%Y', localtime(time)) . ".gzip";
#gzip scalar($logfile) => scalar($archfile)  or die "gzip failed: $GzipError\n";
#print getpid();
#sleep(2);
#my $i = 0;
#while($i++ < 10){
#	sleep(1);
#}
# Load a YAML stream of 3 YAML documents into Perl data structures.
my $center_manager = CenterFactory::new();
my ($centers, $message) = $center_manager->load_centers_from_yaml_file("configuration/security_centers.conf");
my $channel_manager = CollectionChannelFactory::new();
my ($channels, $mymessage) = $channel_manager->load_channels_from_yaml_file("configuration/collection_channels.conf");

my $channels_by_center = $channel_manager->get_channels_by_center($centers->[0], $channels);
my $stockinfo_queue = Thread::Queue->new();
my $stock_thr = threads->create(\&get);
my $stock_thr_pro = threads->create(\&process);
$stock_thr->join();
$stock_thr_pro->join();

sub get{
	while(1){
		my ($gov_hose, $mssg) = $channel_manager->get_channel_by_name("SSI_HoSE", $channels);
		if (ref($gov_hose)){
				$gov_hose->{DELAY_TIME} = 100;
			 	my ($stock_info_set, $msg) = $gov_hose->get_stock_info_set(500);
			 	if(ref($stock_info_set)){
			 		my $tmp = Dumper($stock_info_set);
					$stockinfo_queue->enqueue($tmp);			
			 	}else{
			 		print Dumper($msg);
			 	}	
		}

	}
}
 
 sub process{
 	while(my $tmp = $stockinfo_queue->dequeue()){
 	
 		my $VAR1;
 		eval($tmp);
 		print total_size($VAR1) . "\n";
 		
 	}
 }
